package com.soft.face.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.arcsoft.face.toolkit.ImageFactory;
import com.soft.face.config.arcsoft.service.FaceEngineService;
import com.soft.face.global.BusinessException;
import com.soft.face.global.ErrorCodeEnum;
import com.soft.face.global.R;
import com.soft.face.service.UserFaceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import java.util.zip.ZipFile;

@Api(tags = "人脸")
@RestController
@RequestMapping("face")
@AllArgsConstructor
public class FaceController {

    private UserFaceService userFaceService;
    private FaceEngineService faceEngineService;

    @PostMapping("upload")
    @ApiOperation(value = "人脸数据上传", notes = "文件夹代表一类文件, 并且每一类文件夹下的图片的数量必须一致")
    public R<?> upload(@RequestPart MultipartFile multipartFile) throws Exception {
        String name = multipartFile.getName();
        if (!name.endsWith(".zip")) {
            return R.failed(ErrorCodeEnum.PARAM_ERROR, "上传文件必须是zip格式");
        }
        File tempFile = File.createTempFile(IdUtil.fastUUID(), ".zip");
        File file = FileUtil.writeFromStream(multipartFile.getInputStream(), tempFile);
        ZipFile zipFile = new ZipFile(file, Charset.forName("gbk"));
        userFaceService.upload(zipFile);
        userFaceService.cache();
        return R.success();
    }

    @PostMapping("compare")
    @ApiOperation(value = "人脸对比")
    public R<?> compare(@RequestPart MultipartFile file1, @RequestPart MultipartFile file2) throws Exception {
        Float similar = faceEngineService.compareFace(ImageFactory.getRGBData(file1.getInputStream()), ImageFactory.getRGBData(file2.getInputStream()));
        return R.success(similar);
    }

    @PostMapping("analyse")
    @ApiOperation(value = "分析", notes = "[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]")
    public R<JSONObject> analyse(@RequestBody List<Float> thresholds) throws Exception {
        if (CollectionUtils.isEmpty(thresholds)) {
            throw new BusinessException("阈值列表不能为空");
        }
        return R.success(userFaceService.analyse(thresholds));
    }

}
